package br.edu.utfpr.backuptools.BackupTools.util.quartz;

import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.impl.StdSchedulerFactory;

import br.edu.utfpr.backuptools.BackupTools.util.quartz.interfaces.QuartzProvider;
import br.edu.utfpr.backuptools.BackupTools.util.quartz.jobs.GerarBackup;
import br.edu.utfpr.backuptools.BackupTools.view.telas.principal.JanelaPrincipal;

/**
 * Classe reponsavel por criar a configura��o e agendar as tarefas.
 * 
 * @author Luan Malguti Reffatti
 * 
 */
public class QuartzConfigure implements QuartzProvider {

	public static final String NOME_JOB = "gera_banco";
	SchedulerFactory schedFact;
	Scheduler sched;
	Trigger trigger;
	JobDetail job;
	
	static int version = 1;

	@Override
	public void configure(int horas, int minutos)
			throws SchedulerException {
		try {
			schedFact = new StdSchedulerFactory();
			sched = schedFact.getScheduler();

			job = JobBuilder.newJob(GerarBackup.class).withIdentity(NOME_JOB, Scheduler.DEFAULT_GROUP).build();

			trigger = TriggerBuilder
					.newTrigger()
					.withIdentity("trigger", Scheduler.DEFAULT_GROUP)
					.withSchedule(CronScheduleBuilder.cronSchedule("0 " + minutos+ " " + horas + " ? * *"))// "0 " + minute +// " " + hour +// " ? * *"
					.build();

			sched.scheduleJob(job, trigger);
			sched.start();
			
			JanelaPrincipal.addLog("Backups agendados para " + horas + ":"+ minutos);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void reConfigure(int horas, int minutos) {
		try {
			//pausa o job e a trigger atual
			sched.pauseJob(job.getKey());
			sched.pauseTrigger(trigger.getKey());
			
			//aumenta a versão da configuração
			version++;
			
			//cria um novo job
			JobDetail job2 = JobBuilder.newJob(GerarBackup.class).withIdentity("job_"+version, Scheduler.DEFAULT_GROUP).build();
			
			//cria uma nova trigger 
			Trigger trigger2 = TriggerBuilder
			.newTrigger()
			.withIdentity("trigger"+version, Scheduler.DEFAULT_GROUP)
			.withSchedule(CronScheduleBuilder.cronSchedule("0 " + minutos+ " " + horas + " ? * *"))// "0 " + minute +// " " + hour +// " ? * *"
			.build();
			
			sched.scheduleJob(job2, trigger2);
			sched.start();
			
			//atualiza o job e a trigger antiga
			job = job2;
			trigger = trigger2;

			JanelaPrincipal.addLog("Backups agendados para " + horas + ":"+ minutos);
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}

}
